<template>
  <div class="note-list">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>

    <!-- 空状态 -->
    <div v-else-if="notes.length === 0" class="empty-container">
      <el-empty :description="t('favorites.notes.emptyState')">
        <el-button type="primary" @click="handleCreateNote">
          {{ t('favorites.notes.createFirst') }}
        </el-button>
      </el-empty>
    </div>

    <!-- 列表视图 -->
    <div v-else-if="viewMode === 'list'" class="list-view">
      <el-table
        :data="notes"
        style="width: 100%"
        @row-dblclick="handleRowDoubleClick"
      >
        <el-table-column :label="t('favorites.notes.title')" min-width="300">
          <template #default="{ row }">
            <div class="note-info">
              <div class="note-icon">
                <el-icon :size="20" :color="row.isFavorite ? '#f56c6c' : '#909399'">
                  <Star v-if="row.isFavorite" />
                  <Document v-else />
                </el-icon>
              </div>
              <div class="note-details">
                <div class="note-title">{{ row.title }}</div>
                <div class="note-preview" v-html="getRenderedPreview(row.content || row.markdownContent)"></div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column :label="t('favorites.notes.folder')" width="120">
          <template #default="{ row }">
            <el-tag size="small" v-if="row.folder">
              {{ row.folder.name }}
            </el-tag>
            <span v-else class="text-secondary">-</span>
          </template>
        </el-table-column>

        <el-table-column :label="t('favorites.notes.tags')" width="200">
          <template #default="{ row }">
            <div class="note-tags">
              <el-tag 
                v-for="tag in row.tags?.slice(0, 3)" 
                :key="tag.id"
                size="small"
                :color="tag.color"
                style="margin-right: 4px;"
              >
                {{ tag.name }}
              </el-tag>
              <el-tag v-if="row.tags?.length > 3" size="small" type="info">
                +{{ row.tags.length - 3 }}
              </el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column :label="t('favorites.notes.updateTime')" width="160">
          <template #default="{ row }">
            {{ formatDate(row.updatedAt) }}
          </template>
        </el-table-column>

        <el-table-column :label="t('favorites.notes.actions')" width="250" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                type="primary"
                size="small"
                :icon="Edit"
                @click.stop="handleEdit(row)"
              >
                {{ t('favorites.notes.edit') }}
              </el-button>
              <el-button
                :type="row.isFavorite ? 'warning' : 'success'"
                size="small"
                :icon="Star"
                @click.stop="handleToggleFavorite(row)"
              >
                {{ row.isFavorite ? t('favorites.notes.unfavorite') : t('favorites.notes.favorite') }}
              </el-button>
              <el-dropdown @command="(command) => handleAction(command, row)">
                <el-button size="small" :icon="More" />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="copy">
                      <el-icon><DocumentCopy /></el-icon>
                      {{ t('favorites.notes.copy') }}
                    </el-dropdown-item>
                    <el-dropdown-item command="export">
                      <el-icon><Download /></el-icon>
                      {{ t('favorites.notes.export') }}
                    </el-dropdown-item>
                    <el-dropdown-item divided command="delete">
                      <el-icon><Delete /></el-icon>
                      {{ t('favorites.notes.delete') }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 网格视图 -->
    <div v-else class="grid-view">
      <div class="note-grid">
        <div
          v-for="note in notes"
          :key="note.id"
          class="note-card"
          @dblclick="handleCardDoubleClick(note)"
        >
          <div class="card-header">
            <div class="note-title">{{ note.title }}</div>
            <div class="card-actions">
              <el-button
                type="primary"
                size="small"
                :icon="Edit"
                circle
                @click.stop="handleEdit(note)"
                title="编辑便签"
              />
              <el-button
                :type="note.isFavorite ? 'warning' : 'success'"
                size="small"
                :icon="Star"
                circle
                @click.stop="handleToggleFavorite(note)"
                title="收藏便签"
              />
              <el-dropdown @command="(command) => handleAction(command, note)">
                <el-button size="small" :icon="More" circle @click.stop />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="copy">复制便签</el-dropdown-item>
                    <el-dropdown-item command="export">导出Markdown</el-dropdown-item>
                    <el-dropdown-item divided command="delete">删除便签</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>

          <div class="card-content">
            <div class="note-preview" v-html="getRenderedPreview(note.content || note.markdownContent)">
            </div>
            <div class="note-tags" v-if="note.tags?.length">
              <el-tag 
                v-for="tag in note.tags.slice(0, 2)" 
                :key="tag.id"
                size="small"
                :color="tag.color"
              >
                {{ tag.name }}
              </el-tag>
              <el-tag v-if="note.tags.length > 2" size="small" type="info">
                +{{ note.tags.length - 2 }}
              </el-tag>
            </div>
          </div>

          <div class="card-footer">
            <div class="note-folder" v-if="note.folder">
              <el-icon><Folder /></el-icon>
              {{ note.folder.name }}
            </div>
            <div class="note-time">
              {{ formatDate(note.updatedAt) }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container" v-if="notes.length > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="props.total"
        :page-sizes="[20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 便签查看对话框 -->
    <NoteViewDialog
      v-model:visible="showNoteView"
      :note="viewingNote"
      @edit="handleEditFromView"
      @toggle-favorite="handleToggleFavorite"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import {
  Star, Document, Edit, More, DocumentCopy,
  Download, Delete, Folder
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import NoteViewDialog from './NoteViewDialog.vue'
import { formatDate } from '@/utils/date'
import { noteApi } from '@/api/note'

// 国际化
const { t } = useI18n()

// Props
interface Props {
  notes: any[]
  loading: boolean
  viewMode: 'list' | 'grid'
  total?: number
}

const props = withDefaults(defineProps<Props>(), {
  total: 0
})

// Emits
const emit = defineEmits<{
  'select': [note: any]
  'edit': [note: any]
  'delete': [note: any]
  'toggle-favorite': [note: any]
  'page-change': [page: number, size: number]
  'create': []
}>()

// 响应式数据
const currentPage = ref(1)
const pageSize = ref(20)
const showNoteView = ref(false)
const viewingNote = ref(null)

// 事件处理
const handleRowClick = (row: any) => {
  emit('select', row)
}

const handleRowDoubleClick = (row: any) => {
  viewingNote.value = row
  showNoteView.value = true
}

const handleCardDoubleClick = (note: any) => {
  viewingNote.value = note
  showNoteView.value = true
}

const handleEditFromView = (note: any) => {
  emit('edit', note)
}

const handleEdit = (note: any) => {
  emit('edit', note)
}

const handleToggleFavorite = (note: any) => {
  emit('toggle-favorite', note)
}

const handleCreateNote = () => {
  // 触发创建便签事件
  emit('create')
}

const handleAction = async (command: string, note: any) => {
  switch (command) {
    case 'copy':
      await handleCopyNote(note)
      break
    case 'export':
      await handleExportNote(note)
      break
    case 'delete':
      await handleDeleteNote(note)
      break
  }
}

const handleCopyNote = async (note: any) => {
  // TODO: 实现复制便签
  console.log('Copy note:', note)
  ElMessage.info('复制功能开发中...')
}



const handleExportNote = async (note: any) => {
  try {
    console.log('开始导出便签:', note.id)

    // 使用fetch API直接请求
    const token = localStorage.getItem('token')
    const response = await fetch(`/api/notes/${note.id}/export/markdown`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })

    console.log('Fetch响应状态:', response.status)

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }

    // 获取响应文本
    const markdownContent = await response.text()
    console.log('获取到内容长度:', markdownContent.length)

    if (!markdownContent) {
      throw new Error('导出内容为空')
    }

    // 创建下载链接
    const blob = new Blob([markdownContent], { type: 'text/markdown;charset=utf-8' })
    const url = window.URL.createObjectURL(blob)

    // 生成文件名
    const fileName = `${note.title || '便签'}_${new Date().toISOString().slice(0, 10)}.md`

    console.log('准备下载文件:', fileName)

    // 创建下载链接并触发下载
    const link = document.createElement('a')
    link.href = url
    link.download = fileName
    document.body.appendChild(link)
    link.click()

    // 清理
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('导出成功')

  } catch (error: any) {
    console.error('导出便签失败:', error)
    ElMessage.error('导出失败: ' + (error.message || '未知错误'))
  }
}

const handleDeleteNote = async (note: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除便签"${note.title}"吗？`,
      '删除便签',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    emit('delete', note)
  } catch (error) {
    // 用户取消
  }
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  emit('page-change', currentPage.value, size)
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  emit('page-change', page, pageSize.value)
}

// 工具函数
const getContentPreview = (content: string) => {
  if (!content) return t('favorites.notes.noContent')

  // 简单的Markdown渲染，然后提取纯文本预览
  let rendered = content
    // 标题转换
    .replace(/^### (.*$)/gim, '$1')
    .replace(/^## (.*$)/gim, '$1')
    .replace(/^# (.*$)/gim, '$1')
    // 粗体和斜体转换
    .replace(/\*\*(.*?)\*\*/gim, '$1')
    .replace(/\*(.*?)\*/gim, '$1')
    // 代码块转换
    .replace(/```[\s\S]*?```/gim, '[代码块]')
    .replace(/`(.*?)`/gim, '$1')
    // 链接转换
    .replace(/\[([^\]]+)\]\([^)]+\)/gim, '$1')
    // 移除其他HTML标签
    .replace(/<[^>]*>/g, '')
    // 移除多余的换行和空格
    .replace(/\n+/g, ' ')
    .replace(/\s+/g, ' ')
    .trim()

  return rendered.length > 100 ? rendered.substring(0, 100) + '...' : rendered
}

// 获取渲染后的HTML预览
const getRenderedPreview = (content: string) => {
  if (!content) return `<span class="empty-content">${t('favorites.notes.noContent')}</span>`

  // 简单的Markdown渲染
  let html = content
    // 标题
    .replace(/^### (.*$)/gim, '<h3 class="preview-h3">$1</h3>')
    .replace(/^## (.*$)/gim, '<h2 class="preview-h2">$1</h2>')
    .replace(/^# (.*$)/gim, '<h1 class="preview-h1">$1</h1>')
    // 粗体
    .replace(/\*\*(.*?)\*\*/gim, '<strong>$1</strong>')
    // 斜体
    .replace(/\*(.*?)\*/gim, '<em>$1</em>')
    // 代码块
    .replace(/```([\s\S]*?)```/gim, '<div class="preview-code-block"><code>$1</code></div>')
    // 行内代码
    .replace(/`(.*?)`/gim, '<code class="preview-inline-code">$1</code>')
    // 链接
    .replace(/\[([^\]]+)\]\(([^)]+)\)/gim, '<a href="$2" target="_blank" class="preview-link">$1</a>')
    // 换行
    .replace(/\n/gim, '<br>')

  // 截取预览长度（基于HTML长度，但保持标签完整）
  if (html.length > 200) {
    // 简单截取，可能会截断标签，所以我们用更安全的方式
    const tempDiv = document.createElement('div')
    tempDiv.innerHTML = html
    const textContent = tempDiv.textContent || tempDiv.innerText || ''

    if (textContent.length > 100) {
      // 重新渲染截取后的内容
      const truncatedText = textContent.substring(0, 100) + '...'
      return truncatedText.replace(/\n/g, '<br>')
    }
  }

  return html
}
</script>

<style scoped>
.note-list {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.loading-container {
  padding: 20px;
}

.empty-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.list-view {
  flex: 1;
}

.note-info {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.note-icon {
  flex-shrink: 0;
  margin-top: 2px;
}

.note-details {
  flex: 1;
  min-width: 0;
}

.note-title {
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 4px;
}

.note-preview {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 预览内容样式 */
.note-preview :deep(.preview-h1),
.note-preview :deep(.preview-h2),
.note-preview :deep(.preview-h3) {
  font-size: 13px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0 0 4px 0;
  line-height: 1.2;
}

.note-preview :deep(.preview-h1) {
  font-size: 14px;
}

.note-preview :deep(.preview-h2) {
  font-size: 13px;
}

.note-preview :deep(.preview-h3) {
  font-size: 12px;
}

.note-preview :deep(strong) {
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.note-preview :deep(em) {
  font-style: italic;
  color: var(--el-text-color-regular);
}

.note-preview :deep(.preview-inline-code) {
  background: var(--el-fill-color-light);
  padding: 1px 4px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
  font-size: 11px;
}

.note-preview :deep(.preview-code-block) {
  background: var(--el-fill-color-light);
  padding: 4px 6px;
  border-radius: 4px;
  margin: 2px 0;
  font-family: 'Courier New', monospace;
  font-size: 11px;
  border-left: 3px solid var(--el-color-primary);
}

.note-preview :deep(.preview-link) {
  color: var(--el-color-primary);
  text-decoration: none;
}

.note-preview :deep(.preview-link):hover {
  text-decoration: underline;
}

.note-preview :deep(.empty-content) {
  color: var(--el-text-color-placeholder);
  font-style: italic;
}

.note-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.action-buttons {
  display: flex;
  gap: 4px;
}

.text-secondary {
  color: var(--el-text-color-secondary);
}

.grid-view {
  flex: 1;
}

.note-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  padding: 8px;
}

.note-card {
  border: 1px solid var(--el-border-color);
  border-radius: 8px;
  padding: 16px;
  background: var(--el-bg-color);
  cursor: pointer;
  transition: all 0.2s;
  height: 200px;
  display: flex;
  flex-direction: column;
}

.note-card:hover {
  border-color: var(--el-color-primary);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.card-header .note-title {
  flex: 1;
  font-weight: 600;
  font-size: 16px;
  line-height: 1.4;
  margin-bottom: 0;
  margin-right: 8px;
}

.card-actions {
  display: flex;
  gap: 4px;
  flex-shrink: 0;
}

.card-content {
  flex: 1;
  margin-bottom: 12px;
}

.card-content .note-preview {
  margin-bottom: 8px;
  height: 60px;
  overflow: hidden;
  line-height: 1.3;
}

/* 网格视图中的预览样式 */
.card-content .note-preview :deep(.preview-h1),
.card-content .note-preview :deep(.preview-h2),
.card-content .note-preview :deep(.preview-h3) {
  font-size: 12px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0 0 2px 0;
  line-height: 1.2;
}

.card-content .note-preview :deep(strong) {
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.card-content .note-preview :deep(.preview-inline-code) {
  background: var(--el-fill-color-light);
  padding: 1px 3px;
  border-radius: 2px;
  font-family: 'Courier New', monospace;
  font-size: 10px;
}

.card-content .note-preview :deep(.preview-code-block) {
  background: var(--el-fill-color-light);
  padding: 2px 4px;
  border-radius: 3px;
  margin: 1px 0;
  font-family: 'Courier New', monospace;
  font-size: 10px;
  border-left: 2px solid var(--el-color-primary);
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.note-folder {
  display: flex;
  align-items: center;
  gap: 4px;
}

.pagination-container {
  padding: 16px;
  border-top: 1px solid var(--el-border-color);
  background: var(--el-bg-color);
}
</style>
